import React from 'react';
import {connect} from "dva";
import {Table, Row, Col, Form, Input, Icon, InputNumber, Select, Button, message} from 'antd';
import SingleDragger from "../../commons/SingleDragger";
import Constants from "../../../utils/Constants";

const R = require('ramda');
const {TextArea} = Input;
const FormItem = Form.Item;


export default connect(({lessee}) => ({lessee}))(Form.create({wrappedComponentRef: true})(class AccountInfos extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                open: false,
                disabled: true,
                statementUrl: "",
                secondPayeeList: [],
                individualId: null
            }
        }

        count = 1;
        payCount = 1;


        handleResetFields = () => {
            this.props.form.resetFields();
        }

        handleConfirm = () => {
            let flag = false;

            // let url = this.refs.statementUrl.getUrl();
            // if (R.isNil(url) || R.isEmpty(url)) {
            //     message.error("请先上传转账确认函");
            //     return;
            // }

            this.props.form.validateFields((errors, values) => {
                if (errors) return;
                flag = true;

                if (values.unpayamount <= 0) {
                    message.info("本单应退金额小于0");
                    flag = false;
                    return;
                }

                if (values.transferamount <= 0) {
                    message.info("实退金额应小于0");
                    flag = false;
                    return;
                }

                if (values.unpayamount < values.transferamount) {
                    message.error("实退金额应小于本单应退金额");
                    flag = false;
                    return;
                }

                let lesseeResourceIds = this.props.businessType === Constants.NUMBER_TWO ? this.state.secondPayeeList : [];
                // if(this.props.businessType === Constants.NUMBER_TWO && lesseeResourceIds.length < 1){
                //     message.error("第二收款人信息不能为空！");
                //     flag = false;
                //     return;
                // }
                let secondPaycount = null;
                R.map((row) => {
                    secondPaycount += R.isNil(row.amount) || R.isEmpty(row.amount) ? 0 : row.amount;
                }, lesseeResourceIds)

                secondPaycount = secondPaycount ? secondPaycount.toFixed(4) : null;
                if(secondPaycount && this.props.businessType === "2" && secondPaycount != values.transferamount){
                    message.error("第二收款人金额总和应等于本单实退金额！");
                    flag = false;
                    return;
                }
                lesseeResourceIds = JSON.stringify(lesseeResourceIds);

                //创建结算单

                let recAccs = R.isNil(this.props.customerManage.recAcc) ? null : this.props.customerManage.recAcc;
                let onePayee = this.props.lessee && this.props.lessee.lesseeResourse ? this.props.lessee.lesseeResourse : null;


                let accname = this.props.businessType === Constants.NUMBER_TWO ? (R.isNil(onePayee.payeename) ? "" : onePayee.payeename) : (R.isNil(recAccs) ? "" : recAccs.list[0].payeename);
                let accopenbank = this.props.businessType === Constants.NUMBER_TWO ? (R.isNil(onePayee.bankbranch) ? "" : onePayee.bankbranch) : (R.isNil(recAccs) ? "" : recAccs.list[0].bankbranch);
                let accno = this.props.businessType === Constants.NUMBER_TWO ? (R.isNil(onePayee.payeeno) ?  "" : onePayee.payeeno) : (R.isNil(recAccs) ? "" : recAccs.list[0].payeeno);
                let payeename = this.props.businessType === Constants.NUMBER_TWO ? (R.isNil(onePayee.payeename) ? "" : onePayee.payeename) : (R.isNil(recAccs) ? "" : recAccs.list[0].payeename);

                let url = this.refs.statementUrl.getUrl();
                let filename = "";
                if (!R.isNil(url) && !R.isEmpty(url)) {
                    filename = url.substring(url.lastIndexOf('/') + 1, url.length);
                }


                let payload = this.props.payload;

                let forex = this.props.statementType == "2" ? this.props.customerManage.statetemntDetail.forex : [];
                let deposit = this.props.statementType == "2" ? this.props.customerManage.statetemntDetail.deposit : [];

                let forexIds = this.props.statementType == "2" ? [] : payload.forexIds;
                let depositids = this.props.statementType == "2" ? [] : payload.depositids;

                if (!R.isNil(forex)) {
                    for (let i = 0; i < forex.length; i++) {
                        forexIds.push(forex[i].id)
                    }
                }

                if (!R.isNil(deposit)) {
                    for (let i = 0; i < deposit.length; i++) {
                        depositids.push(deposit[i].id)
                    }
                }

                let amount = values.unpayamount - values.transferamount;
                let memo = values.memo;

                let path = this.props.businessType === Constants.NUMBER_TWO ? "customerManage/createMpStatement" : "customerManage/addStatement";
                this.props.dispatch({
                    type: path,
                    payload: {
                        cstid: this.props.cstId,
                        type: this.props.statementType,
                        transferamount: values.transferamount,
                        unpayamount: amount,
                        filename: filename,
                        url: url,
                        accname: accname,
                        accopenbank: accopenbank,
                        accno: accno,
                        memo: memo,

                        orderIds: payload.orderIds,
                        historyAmtIds: payload.historyAmtIds,
                        forexIds: forexIds,
                        depositids: depositids,
                        orderChargesIds: payload.orderChargesIds,
                        statementMpStr: lesseeResourceIds,
                        payman: payeename,

                    }
                })
            });

            return flag;
        }


        /**
         * 有订单模式 计算应支付金额
         */
        getUnpayamount = () => {
            let statetemntDetail = this.props.customerManage.statetemntDetail;

            let account = 0;

            let forex = this.props.statementType == "2" ? this.props.customerManage.statetemntDetail.forex : this.props.customerManage.statetemntDetail.forexs;
            let deposit = this.props.statementType == "2" ? this.props.customerManage.statetemntDetail.deposit : this.props.customerManage.statetemntDetail.deposits;


            //历史余额
            let historyAmtList = this.props.customerManage.historyAmtList;
            let historyAmtIds = this.props.payload.historyAmtIds;

            /**
             * 应支付
             */
            if (!R.isEmpty(historyAmtList) && !R.isEmpty(historyAmtIds)) {
                for (let i = 0; i < historyAmtList.length; i++) {
                    if (R.contains(historyAmtList[i].id, historyAmtIds)) {
                        account += Number(historyAmtList[i].amount);
                    }
                }
            }

            if (!R.isNil(forex) && !R.isEmpty(forex)) {
                for (let i = 0; i < forex.length; i++) {
                    account += Number(forex[i].actualamount);
                }

            }
            if (!R.isNil(statetemntDetail.taxRefundFinance) && !R.isEmpty(statetemntDetail.taxRefundFinance)) {
                for (let i = 0; i < statetemntDetail.taxRefundFinance.length; i++) {
                    account += Number(statetemntDetail.taxRefundFinance[i].amount);
                }
            }

            if (!R.isNil(statetemntDetail.depositRecord) && !R.isEmpty(statetemntDetail.depositRecord)) {
                for (let i = 0; i < statetemntDetail.depositRecord.length; i++) {
                    account += Number(statetemntDetail.depositRecord[i].amount);
                }
            }


            /**
             *
             * 应扣减
             */
            if (!R.isNil(deposit) && !R.isEmpty(deposit)) {
                for (let i = 0; i < deposit.length; i++) {
                    account -= deposit[i].amount;
                }
            }

            let payload = this.props.payload;
            // if (!R.isNil(statetemntDetail.orderCharge) && !R.isEmpty(statetemntDetail.orderCharge)) {
            //     for (let i = 0; i < statetemntDetail.orderCharge.length; i++) {
            //         account -= statetemntDetail.orderCharge[i].cost;
            //     }
            // }
            if (!R.isNil(payload.orderChargesStatement) && !R.isEmpty(payload.orderChargesStatement)) {
                for (let i = 0; i < payload.orderChargesStatement.length; i++) {
                    account -= payload.orderChargesStatement[i];
                }
            }
            account = account.toFixed(4);

            return account;

        }

        /**
         * 有订单模式  计算应支付金额
         * @returns {number}
         */
        getNoOOrderUnpayamount = () => {
            let statetemntDetail = this.props.customerManage.statetemntDetail;

            let account = 0;
            let forex = this.props.customerManage.statetemntDetail.forexs;


            //历史余额
            let historyAmtList = this.props.customerManage.historyAmtList;
            let historyAmtIds = this.props.payload.historyAmtIds;

            /**
             * 应支付
             */
            if (!R.isEmpty(historyAmtList) && !R.isEmpty(historyAmtIds)) {
                for (let i = 0; i < historyAmtList.length; i++) {
                    if (R.contains(historyAmtList[i].id, historyAmtIds)) {
                        account += Number(historyAmtList[i].amount);
                    }
                }
            }

            //外汇
            let forexIds = this.props.payload.forexIds;

            if ((!R.isNil(forex) && !R.isEmpty(forex)) && (!R.isEmpty(forexIds) || !R.isNil(forexIds))) {
                for (let j = 0; j < forexIds.length; j++) {
                    for (let i = 0; i < forex.length; i++) {
                        if (forexIds[j] == forex[i].id) {
                            account += Number(forex[i].actualamount);
                        }
                    }
                }
            }

            let deposit = this.getNoOrderDeposit();
            //释放保证金
            let depositRecords = this.getNoOrderDepositRecord(deposit);

            if (!R.isEmpty(depositRecords)) {
                for (let i = 0; i < depositRecords.length; i++) {
                    account += Number(depositRecords[i].amount);
                }
            }

            /**
             *
             * 应扣减
             */

            //保证金
            if (!R.isNil(deposit) && !R.isEmpty(deposit)) {
                for (let i = 0; i < deposit.length; i++) {
                    account -= deposit[i].amount;
                }
            }

            account = account.toFixed(4);
            return account;

        }

        onAdd = () => {
            let secondPayeeList = this.state.secondPayeeList;
            secondPayeeList.push({id: this.payCount++});
            this.setState({secondPayeeList});
        }

        onDelete = (id) => {
            let secondPayeeList = this.state.secondPayeeList;
            secondPayeeList.splice(secondPayeeList.findIndex(item => item.id === id), 1);
            this.setState({secondPayeeList});
        }

        refreshInputNumber = (id, paymanId, e) => {
            let secondPayeeList = this.state.secondPayeeList;
            secondPayeeList.map(item => {
                if (item.id === id) {
                    item.amount = e;
                    item.paymanId = paymanId
                }
            });
            this.setState(secondPayeeList);
        }

        refreshSelect = (e) => {
            this.setState({individualId: e});
        }

        getPayColumns = () => {
            let recAccsList = this.props.customerManage && this.props.customerManage.recAccsList ? this.props.customerManage.recAccsList : [];

            let payColumns = [
                {
                    title: '第二收款人', dataIndex: 'weight', key: 'weight', width: '45%', render: (text, record, index) => {
                        return <Select style={{width: '96%'}} showSearch
                                       placeholder="可通过输入关键字搜索"
                                       filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                        onChange={this.refreshSelect.bind(this)}>
                            {
                                recAccsList.map(item => {
                                    return (<Select.Option value={item.id} key={item.id}>{item.payeename}</Select.Option>);
                                })
                            }
                        </Select>
                        // <InputNumber maxLength="18" value={record.weight} style={{ width: '96%' }} onChange={this.refreshInputNumber.bind(this, record.id, 'weight', 'pay')} />
                    }
                },
                {
                    title: '实退金额', dataIndex: 'count', key: 'count', width: '45%', render: (text, record, index) => {
                        return <InputNumber maxLength="11" style={{width: '100%'}}
                                            onChange={this.refreshInputNumber.bind(this, record.id, this.state.individualId)}/>
                    }
                }
            ];
            payColumns.push({
                key: 'delete', width: '10%', render: (text, record, index) => {
                    return <Button type="primary" icon="delete" style={{marginRight: 5}} size={'small'}
                                   onClick={this.onDelete.bind(this, record.id)}/>
                }
            })
            return payColumns;
        }

        /**
         * 无订单 保证金
         * @returns {Array}
         */
        getNoOrderDeposit = () => {
            let deposit = [];
            let selectDeposit = [];
            let forexIds = this.props.payload.forexIds;

            if (R.isEmpty(forexIds) || R.isNil(forexIds)) {
                return deposit;
            }

            deposit = this.props.customerManage.statetemntDetail.deposits;

            if (R.isNil(deposit) || R.isEmpty(deposit)) {
                return deposit;
            }

            for (let i = 0; i < forexIds.length; i++) {
                for (let j = 0; j < deposit.length; j++) {
                    if (forexIds[i] == deposit[j].forexid) {
                        selectDeposit.push(deposit[j])
                    }
                }
            }

            return selectDeposit;

        }

        /**
         * 无订单 释放保证金
         * @returns {Array}
         */
        getNoOrderDepositRecord = (deposits) => {
            let depositRecords = [];
            let depositRecordIds = [];
            let selectDepositRecords = [];

            if (R.isEmpty(deposits) || R.isNil(deposits)) {
                return depositRecords;
            }

            depositRecords = this.props.customerManage.statetemntDetail.depositRecord;

            if (R.isNil(depositRecords) || R.isEmpty(depositRecords)) {
                return depositRecords;
            }

            for (let i = 0; i < deposits.length; i++) {
                for (let j = 0; j < depositRecords.length; j++) {
                    if (deposits[i].id == depositRecords[j].depositid) {
                        if (!R.contains(depositRecords[j].id, depositRecordIds)) {
                            selectDepositRecords.push(depositRecords[j]);
                        }

                    }
                }
            }
            return selectDepositRecords;
        }


        render() {
            const {getFieldDecorator} = this.props.form;
            const formItemLayout = {labelCol: {xs: {span: 8}, sm: {span: 8}}, wrapperCol: {xs: {span: 15}, sm: {span: 14}}};
            let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;


            let unpayamount = this.props.statementType == "2" ? this.getUnpayamount() : this.getNoOOrderUnpayamount();

            const divWithOutBorderBottom = {
                display: 'flex',
                border: '1px solid rgb(233,233,233)',
                padding: '3px',
                borderSpacing: '0px',
                lineHeight: '2',
                textAlign: 'left',
                marginBottom: '25px'
            }

            return (

                <Form>
                    <Row>
                        <Col span={11}>
                            <FormItem {...formItemLayout} label="本单应退金额" hasFeedback>
                                {getFieldDecorator('unpayamount', {
                                    initialValue: unpayamount
                                })(
                                    <InputNumber style={{width: '100%'}} maxLength="20" disabled={true}/>
                                )}
                            </FormItem></Col>
                        <Col span={11}>
                            <FormItem {...formItemLayout} label="本单实退金额" hasFeedback>
                                {getFieldDecorator('transferamount', {
                                    rules: [{
                                        required: true, message: '请输入本单实退金额'
                                    }],
                                    initialValue: unpayamount
                                })(
                                    <InputNumber style={{width: '100%'}} maxLength="20"/>
                                )}
                            </FormItem></Col>
                    </Row>
                    {this.props.businessType === Constants.NUMBER_TWO ?
                        <div style={divWithOutBorderBottom}>
                            <div style={{width: '20%', textAlign: 'center', borderRight: '1px solid #e9e9e9'}}><Button
                                type="primary" icon="plus" size={'small'}
                                onClick={this.onAdd.bind()}>{"第二收款人(" + this.state.secondPayeeList.length + ")"}</Button>
                            </div>
                            <div style={{
                                width: '100%',
                                // display: dataSource.secondPayeeList && this.state.secondPayeeList.length > 0 ? 'inline-block' : 'none'
                            }}>
                                <Table bordered={false} className="customTableSmall" loading={this.props.loading}
                                       rowKey='id' dataSource={this.state.secondPayeeList} columns={this.getPayColumns()}
                                       bordered={false} size={'small'} pagination={false}/>
                            </div>
                        </div>
                        : ""}
                    <Row>
                        <Col span={11}>
                            <FormItem {...formItemLayout} label="出货备注" hasFeedback>
                                {getFieldDecorator('memo', {
                                    rules: [{
                                        required: true, message: '请输入本单出货备注'
                                    }],
                                    initialValue: ""
                                })(
                                    <TextArea autosize={{minRows: 2, maxRows: 10}} maxLength="500"/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={11}>
                            <FormItem {...formItemLayout} label="转账确认函" hasFeedback>
                                <SingleDragger url={dataSource.statementUrl} ref="statementUrl" dataSource={dataSource}
                                               module={this.state.module}/>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            );
        }
    })
)

// WEBPACK FOOTER //
// ./public/src/components/order/components/AccountInfos.js